package demo.flyweight;


import java.nio.ByteBuffer;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @author : feixiang.li
 * @since : 2025-09-17 20:34
 */
public class Main {

    public static void main(String[] args) throws Exception {
        test3();
    }


    public static void test3() throws Exception {
        BufferPool bufferPool = new BufferPool(512, 256);
        ByteBuffer allocate = bufferPool.allocate(256, 1000);
        ByteBuffer allocate1 = bufferPool.allocate(256, 1000);
        System.out.println(allocate1);
        System.out.println(allocate);

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        FutureTask<ByteBuffer> futureTask = new FutureTask<>(new Callable<ByteBuffer>() {
            @Override
            public ByteBuffer call() throws Exception {
                return bufferPool.allocate(256, 10000);
            }
        });
        executorService.submit(futureTask);

        Thread.sleep(1000);
        bufferPool.dealocate(allocate);

        ByteBuffer byteBuffer = futureTask.get(100, TimeUnit.MILLISECONDS);
        System.out.println(byteBuffer);
        if (byteBuffer == allocate) {
            System.out.println("复用成功");
        }
    }

    public static void test2() throws InterruptedException {
        //        // 申请缓存
        BufferPool bufferPool = new BufferPool(1024, 128);
        ByteBuffer allocate = bufferPool.allocate(1024, 1000);
        allocate.put("hello world".getBytes());
        System.out.println(allocate);
        // 还回 缓存
        bufferPool.dealocate(allocate);

        ByteBuffer allocate1 = bufferPool.allocate(1024, 10000);
        if (allocate1 != null) {
            System.out.println(allocate1);
        }
    }


    public static void test1() throws InterruptedException {
        BufferPool bufferPool = new BufferPool(1024, 256);

        ByteBuffer allocate = bufferPool.allocate(256, 1000);
        if (allocate != null) {
            System.out.println(allocate);
        }
        bufferPool.dealocate(allocate);
        ByteBuffer allocate1 = bufferPool.allocate(256, 1000);
        if (allocate1 == allocate) {
            System.out.println("复用成功");
        }
    }
}
